$(function () {
    if (!localStorage.getItem('token')) {
        var param = $.formatParams(location.href);

        if (!param.code) {
            location.href=location.origin + "/main/wx_login.html"+ (param.company_key ? `?company_key=${param.company_key}` :'');
            return;
        }

        $.cAjax('/crmPc/home/pcLoginCallBack', {
            data: param
        }).then(function (data) {
            localStorage.setItem('info', JSON.stringify(data));
            localStorage.setItem('token', data.token);
            init();
        }).catch(function (err) {
            layer.alert(err.message, {}, function(){
                location.href=location.origin + "/main/wx_login.html" +  (param.company_key ? `?company_key=${param.company_key}` :'');
            })
        });
    } else {
        init();
    }


    function init(){
        var vw = new Vue({
            el: '#main-wrapper',
            // components:{header},
            data: {
                username:'',
                total_user:'',//总用户
                today_new:'',//今日新增
                traded:'',//已成交
                ownCount: '', //独占客户数
                orderAmount: '', // 订单总额
                countOrder: '', //订单总数
                turn_ratio:'',//成交率
                need_follow_today:'',//今日需跟进
                no_follow_days:'7',//未跟进客户天数
                follow_clients:[
                    {src:'https://you-one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/card1_user.png'},
                    {src:'https://you-one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/card1_user.png'},
                    {src:'https://you-one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/card1_user.png'},
                    {src:'https://you-one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/card1_user.png'}
                ],
                has_follow_today:'',//今日已跟进
                no_follow_today:'',//今日未跟进
                has_follow_today_percent:'',
                no_follow_today_percent:'',
                targetMoney:'',//目标金额
                dealMoney:'',// 完成金额
                lackMoney:'',//业绩差额
                dealOrderCount:'',//成单数量
                seeGoodsNum: '0',//浏览量
                orderCount: '0',//下单量
                payCount: '0',//付款量
                seeGoodsNumRate: '0',//下单转化率
                orderCountRate: '0',//付款率
                payCountRate: '0',//成交转化率
                search_key:'',//搜索关键字
                countType: 1,
                salesChart: '',
                dayNum:'30',
                isShowTab: false,
                tabs: [
                    { type: 1, label: '我的统计' },
                    { type: 2, label: '企业统计' },
                ],
                // 今日录入客户列表哦
                newsCustom:[],
                isShowList: false,
            },
            mounted: function(){
                let _this = this;

                try{
                    _this.isShowTab = JSON.parse(localStorage.getItem('info')).roleId != 0;
                }catch (e) {

                }
                this.getCount();
                this.getCountCustomerAnalysis();
                this.getChangeCount();
                this.getSevenData();

            },
            methods: {
                toFollow(){
                    location.href = location.origin + '/main/customerManage.html';
                },
                // 客户兴趣
                initInterestChart: function ([card, prod, dynamic, company]) {
                    c3.generate({
                        bindto: '#customerInterest',
                        data: {
                            columns: [
                                ['对我感兴趣', card],
                                ['喜欢产品', prod],
                                ['关注动态', dynamic],
                                ['看重公司', company],
                            ],

                            type : 'donut',
                        },
                        donut: {
                            label: {
                                show: false
                            },
                            title:"兴趣",
                            width:20,
                        },
                        legend: {
                            hide: true
                        },
                        color: {
                            pattern: ['#FF5C6C', '#7460EE', '#24D2B5', '#20AEE3']
                        }
                    });
                },
                // 业绩差额
                initDifferenceChart: function (differenceRate){
                    c3.generate({
                        bindto: '#sales',
                        data: {
                            columns: [
                                ['差额', differenceRate],
                                ['完成', 100-differenceRate],
                            ],
                            type : 'donut',
                            /*           onclick: function (d, i) { console.log("onclick", d, i); },
                                       onmouseover: function (d, i) { console.log("onmouseover", d, i); },
                                       onmouseout: function (d, i) { console.log("onmouseout", d, i); }*/
                        },
                        padding: {
                            bottom: 20
                        },
                        donut: {
                            label: {
                                show: false
                            },
                            title:"",
                            width:18,
                        },
                        size: {
                            height: 150
                        },
                        legend: {
                            hide: true
                            //or hide: 'data1'
                            //or hide: ['data1', 'data2']
                        },
                        color: {
                            pattern: ['#eceff1', '#24d2b5', '#6772e5', '#20aee3']
                        }
                    });
                },
                // 业绩目标
                initTargetChart: function (rate) {
                    c3.generate({
                        bindto: '#prediction',
                        onrendered: function(){
                            $('#prediction').find('.c3-chart-arcs-gauge-min, .c3-chart-arcs-gauge-max').attr('dy', '1em');
                        },
                        data: {
                            columns: [
                                ['完成率', rate || 0]
                            ],
                            type: 'gauge',
                            // onclick: function (d, i) { console.log("onclick", d, i); },
                            // onmouseover: function (d, i) { console.log("onmouseover", d, i); },
                            // onmouseout: function (d, i) { console.log("onmouseout", d, i); },
                        },
                        color: {
                            pattern: ['#ff9041', '#20aee3', '#24d2b5', '#6772e5'], // the three color levels for the percentage values.
                            threshold: {
                                //            unit: 'value', // percentage is default
                                //            max: 200, // 100 is default
                                values: [30, 60, 90, 100]
                            }
                        },
                        gauge: {
                            width:22,
                        },
                        size: {
                            height: 120,
                            width:150
                        }
                    });
                },
                //  近7日成交额
                initSalesChart: function (data){
                    $('#sales-chart').html('');

                    let yKeys = ['order', 'deal',];
                    let labels = ['商城订单', '个人完成订单'];

                    if (this.countType == 2) {
                        yKeys.push('company');
                        labels.push('企业成交订单')
                    }

                    this.salesChart = Morris.Area({
                        element: 'sales-chart',
                        data: data || [],
                        xkey: 'date',
                        ykeys: yKeys,
                        labels: labels,
                        xLabels: 'day',
                        pointSize: 0,
                        fillOpacity: 0,
                        pointStrokeColors: ['#20aee3', '#24d2b5', '#6772e5'],
                        gridLineColor: '#e0e0e0',
                        lineWidth: 3,
                        hideHover: 'auto',
                        lineColors: ['#20aee3', '#24d2b5', '#6772e5'],
                        resize: true
                    });
                },
                // 获取统计数据
                getCount: function(){
                    var _this = this;
                    $.cAjax('/crmPc/index/getPcCount', {
                        data: {
                            type: this.countType,
                        }
                    }).then(function (data) {
                        if (data) {
                            _this.newsCustom = data.newCustomerList
                            _this.total_user = data.customerCount;
                            _this.traded = data.dealCount;
                            _this.ownCount = data.ownCount;
                            _this.countOrder = data.orderCount;
                            _this.orderAmount = data.orderAmount;
                            _this.turn_ratio = data.customerCount ? (data.dealCount/data.customerCount*100).toFixed(2) + "%" : "0%";
                            _this.has_follow_today = data.dealFollowCount;
                            _this.no_follow_today = data.ownCount - data.dealFollowCount;
                            _this.no_follow_today = _this.no_follow_today < 0 ? 0 : _this.no_follow_today;
                            _this.dealMoney = (data.dealMoney/100).toFixed(2);
                            _this.dealOrderCount = data.dealOrderCount;
                            _this.today_new = data.newCount;
                            _this.need_follow_today = data.noFollowCount;
                            _this.targetMoney = (data.targetMoney/100).toFixed(2);
                            _this.lackMoney = data.targetMoney <= data.dealMoney ? 0 : data.targetMoney-data.dealMoney;
                            _this.lackMoney = (_this.lackMoney/100).toFixed(2);
                            _this.has_follow_today_percent = data.ownCount ? (_this.has_follow_today / data.ownCount).toFixed(2) * 100 + '%' : '0%';
                            _this.no_follow_today_percent = data.ownCount ? (_this.no_follow_today / data.ownCount).toFixed(2) * 100 + '%' : '0%';

                            let rate = data.targetMoney > 0 ? (data.dealMoney/data.targetMoney*100).toFixed(1) : 100;
                            let differenceRate = _this.targetMoney>0 ? (_this.lackMoney/_this.targetMoney).toFixed(1)*100 : 0;
                            _this.initTargetChart(rate);
                            _this.initDifferenceChart(differenceRate);
                        }

                    }).catch(function (err) {

                    });
                },
                // 获取饼图数据
                getCountCustomerAnalysis: function () {
                    let _this = this;

                    $.cAjax('/crmPc/index/countCustomerAnalysis', {
                        data: {
                            type: this.countType,
                        }
                    }).then(function (data) {
                        if(data){
                            let result = [0,0,0,0];
                            data.map((val)=>{
                                result[val.seeType-1] = val.num
                            })
                            _this.initInterestChart(result);
                        }
                    }).catch(function (err) {

                    });
                },
                //
                // changeDayNum: function(el){
                //     var _this = this;
                //     _this.dayNum = el.val();
                //     this.getChangeCount();
                // },
                // 转化率漏斗
                getChangeCount: function () {
                    var _this = this;
                    $.cAjax('/crmPc/index/getChangeCount', {
                        data: {
                            type: this.countType,
                            dayNum: this.dayNum,
                        }
                    }).then(function (data) {
                        if(data){
                            _this.seeGoodsNum = data.seeGoodsNum,
                            _this.orderCount = data.orderCount,
                            _this.payCount = data.payCount,
                            _this.seeGoodsNumRate =  data.seeGoodsNum ? (data.orderCount / data.seeGoodsNum*100).toFixed(2) + "%" : "0%";
                            _this.orderCountRate = data.orderCount ? (data.payCount / data.orderCount*100).toFixed(2) + "%" : "0%";
                            _this.payCountRate = data.seeGoodsNum ? (data.payCount / data.seeGoodsNum*100).toFixed(2) + "%" : "0%";
                        }
                    }).catch(function (err) {

                    });
                },
                // 获取7日成交额
                getSevenData: function () {
                    let _this = this;
                    $.cAjax('/crmPc/index/sevenData', {
                        data: {
                            type: this.countType,
                        }
                    }).then(function (data) {
                        let chartData = [];
                        data.dealList.map((val, idx)=>{
                            let tmp = {
                                date: val.date,
                                deal: (val.amount/100).toFixed(2),
                                order: (data.orderList[idx].amount/100).toFixed(2),
                            };

                            if (_this.countType == 2) {
                                tmp.company = (data.companyList[idx].amount/100).toFixed(2);
                            }

                            chartData.push(tmp)
                        });

                        _this.initSalesChart(chartData);
                    }).catch(function (err) {

                    });
                },
                search: function(){//搜索
                    console.log(this.search_key)
                }
            },
            watch:{
                dayNum:function () {
                    this.getChangeCount();
                },
                countType(){
                    this.getCount();
                    this.getCountCustomerAnalysis();
                    this.getChangeCount();
                    this.getSevenData();
                }
            }
        })
    }
})

